package validators;

import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import utils.UserDAORemote;

@FacesValidator("validators.EmailValidator")
public class EmailValidator implements Validator {

	private Pattern pattern;
	private Matcher matcher;

	@EJB
	UserDAORemote udr;

	ResourceBundle bundle = ResourceBundle.getBundle(
			"languageSettings.language", FacesContext.getCurrentInstance()
					.getViewRoot().getLocale());
	
	private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*\\."
			+ "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
			+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

	public EmailValidator() {
		pattern = Pattern.compile(EMAIL_PATTERN);
	}

	/**
	 * 
	 */
	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {

		matcher = pattern.matcher((CharSequence) value);

		if (!matcher.matches()) {
			FacesMessage message = new FacesMessage(bundle.getString("Validators_EmailValidator_Error"));
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		}

	}

}
